const express = require('express')
const router = express.Router()
const svgCaptcha = require('svg-captcha');
const ManagerModel = require('../../model/managerModel')

const md5 = require('md5')

router.get('/', function (req, res) {
  // let result = new ManagerModel({
  //   username: 'admin',
  //   password: md5('123456')
  // })
  // await result.save()
  res.render('admin/login/login')
})

router.post('/doLogin', async function (req, res) {
  let username = req.body.username
  let password = req.body.password
  let verify = req.body.verify
  // 1. 判断验证码是否正确
  if((verify && verify.toLocaleLowerCase()) !== (req.session.captcha && req.session.captcha.toLocaleLowerCase())) {
    res.render('admin/public/error', {
      redirectUrl: '/admin/login',
      message: '图形验证码输入错误'
    })
    // res.send('验证错误')
    return;
  }
  // 2. 判断用户名密码是否合法
  try {
    let result = await ManagerModel.find({'username': username, 'password': md5(password)})
    if(result && result.length > 0) {
      // 保存用户信息
      req.session.userInfo = result[0]
      res.render('admin/public/success', {
        redirectUrl: '/admin',
        message: '登录成功'
      })
    } else {
      res.render('admin/public/error', {
        redirectUrl: '/admin/login',
        message: '登录失败，用户名或者密码错误'
      })
    }
  } catch (error) {
    console.log(error)
    res.render('admin/public/error', {
      redirectUrl: '/admin/login',
      message: '登录失败，用户名或者密码错误'
    })
  }
  // res.send('验证成功' + JSON.stringify(req.body))
})

router.get('/verify', function (req, res) {
    var captcha = svgCaptcha.create();
    // 保存验证码
    req.session.captcha = captcha.text;
    
    res.type('svg');
    res.status(200).send(captcha.data);
});

router.get('/loginOut', function (req, res) {
  req.session.userInfo = null
  res.redirect("/admin/login")
})

module.exports = router
